package com.hhxy.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 请求参数的通用方式
 */
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet方法被调用了...");

        /*---------------解决Post请求方式导致的中文乱码问题-------------------*/
        //req.setCharacterEncoding("UTF-8");
        /*--------------------------------------------------------*/

        //1、获取所有请求参数
        Map<String, String[]> maps = req.getParameterMap();//获取键
        for (String key : maps.keySet()) {//遍历所有键
            System.out.print(key+":");
            //获取值
            String[] values = maps.get(key);
            for (String value : values) {
                System.out.println(value+" ");//原始输出，不进行乱码处理
                /*------------解决Get请求方式导致的乱码问题----------------*/
                //也能同时解决Post请求方式导致的乱码问题
                String result = null;
                /*byte[] bytes = value.getBytes(StandardCharsets.ISO_8859_1);
                result = new String(bytes,StandardCharsets.UTF_8);*/
                result = new String(value.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
                System.out.println(result);
                /*--------------------------------------------------------*/
            }
            System.out.println();
        }
        System.out.println("===============================");
        //2、获取单个请求参数（数组）
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {
            System.out.println("hobby:"+hobby);
        }
        System.out.println("================================");
        //3、获取单个请求参数（单个值）
        String hobby = req.getParameter("hobby");
        System.out.println("hobby:"+hobby);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost方法被调用了...");
        this.doGet(req,resp);
    }
}